package me.keiwu.user.controller;

import me.keiwu.pub.data.ResponseV2;
import me.keiwu.pub.util.ContextUtil;
import me.keiwu.user.domain.UserDeliveryAddress;
import me.keiwu.user.service.UserDeliveryAddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/delivery")
public class UserAddressController {

    @Autowired
    private UserDeliveryAddressService userDeliveryAddressService;

    @ResponseBody
    @RequestMapping("/saveAddress")
    public ResponseV2 saveUserAddress(HttpServletRequest request
            , @RequestParam(required = true) String deliveryName
            , @RequestParam(required = true) String deliveryAddress
            , @RequestParam(required = true) String deliveryPhone) {

        Long userId = ContextUtil.getLoginUserId(request);

        UserDeliveryAddress userDeliveryAddress = new UserDeliveryAddress();
        userDeliveryAddress.setUserId(userId);
        userDeliveryAddress.setDeliveryName(deliveryName);
        userDeliveryAddress.setAddress(deliveryAddress);
        userDeliveryAddress.setMobilePhone(deliveryPhone);

        UserDeliveryAddress result = userDeliveryAddressService.saveUserAddress(userDeliveryAddress);
        if (result != null) {
            return ResponseV2.ok(result);
        }else {
            return ResponseV2.fail();
        }

    }

    @ResponseBody
    @RequestMapping("/canFill")
    public ResponseV2 canFillDeliveryAddress(HttpServletRequest request) {
        Long userId = ContextUtil.getLoginUserId(request);
        if (userDeliveryAddressService.hasFilledAddress(userId)) {
            return ResponseV2.fail();
        }
        return ResponseV2.ok();
    }

    @ResponseBody
    @RequestMapping("/sendAddressTmpMsg")
    public ResponseV2 sendAddressTmpMsg(HttpServletRequest request
            , @RequestParam(required = true) Long deliveryUserId
            , @RequestParam(required = true) String gift
            , @RequestParam(required = true) String msg) {
        return userDeliveryAddressService.sendDeliveryAddressTmpMsg(deliveryUserId, gift, msg);
    }
}
